package com.sneaker.shower.controller;

import com.sneaker.shower.common.BizException;
import com.sneaker.shower.entity.dto.WxAuthorizeReqDTO;
import com.sneaker.shower.entity.dto.WxCommonReqDTO;
import com.sneaker.shower.service.WxMpPortalService;
import com.sneaker.shower.util.JacksonUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping("/wx_mp")
@Api("微信公众号相关接口")
@Slf4j
public class WxMpController {

    private final WxMpPortalService wxMpPortalService;

    public WxMpController(WxMpPortalService wxMpPortalService) {
        this.wxMpPortalService = wxMpPortalService;
    }

    @GetMapping("/verify")
    public String verify(WxCommonReqDTO wxCommonReqDTO) {
        log.info("收到微信服务器发送的认证消息：{}", JacksonUtils.writeValueAsString(wxCommonReqDTO));

        return wxMpPortalService.verify(wxCommonReqDTO);
    }

    @PostMapping("/verify")
    public String handleMessage(@RequestBody String body, WxCommonReqDTO wxCommonReqDTO) {
        log.info("收到用户消息：{}", body);
        return wxMpPortalService.handleMsg(body, wxCommonReqDTO);
    }

    @GetMapping("/call_back")
    public void callBackAndJump(WxAuthorizeReqDTO wxAuthorizeReqDTO, HttpServletResponse response) {
        String redirectUrl = wxMpPortalService.jump(wxAuthorizeReqDTO);
        log.info("redirectUrl:{}", redirectUrl);
        try {
            response.sendRedirect(redirectUrl);
        } catch (IOException e) {
            throw new BizException("微信重定向失败");
        }
    }

}
